
rm(list = ls())

# Check if the packages that we need are installed
want = c("foreign","readstata13", "ggthemes","scales","stargazer",
         "tidyverse", "cobalt","ebal","fastDummies", "WeightIt", 
         "rockchalk", "hrbrthemes","jtools",
         "coefplot", "Cairo","ggpubr","cowplot")

have = want %in% rownames(installed.packages())
# Install the packages that we miss
if ( any(!have) ) { install.packages( want[!have] ) }
# Load the packages
junk <- lapply(want, library, character.only = T)
# Remove the objects we created
rm(have, want, junk)

setHook(packageEvent("grDevices", "onLoad"),
        function(...) grDevices::X11.options(type='cairo'))
options(device='x11')

## FIGURE 1 - GOOGLE TRENDS
setwd("/Users/malet/Dropbox/Contagion paper/Replication files/")

# italy
ita<-read.csv("italy2.csv", header = T, sep = ",")
ita <- rename(ita, referendum="referendum...Italy.")
ita <- rename(ita, constitution="costituzione.europea...Italy.")
ita <- rename(ita, week=Week)

df1 <- ita %>%
  select(week, referendum, constitution) %>%
  gather(key = "variable", value = "value", -week)
head(df1)
df1$country <- "Italy"


# belgium
bel<-read.csv("belgium2.csv", header = T, sep = ",")
names(bel)
bel <- rename(bel, referendum="referendum...Belgium.")
bel <- rename(bel, constitution="constitution.europ.enne...Belgium.")
bel <- rename(bel, week=Week)

df2 <- bel %>%
  select(week, referendum, constitution) %>%
  gather(key = "variable", value = "value", -week)
head(df2)
df2$country <- "Belgium"


# germany
ger<-read.csv("germany2.csv", header = T, sep = ",")
names(ger)
ger <- rename(ger, referendum="referendum.Germany.")
ger <- rename(ger, constitution="Verfassung.Germany.")
ger <- rename(ger, week=Week)

df3 <- ger %>%
  select(week, referendum, constitution) %>%
  gather(key = "variable", value = "value", -week)
head(df3)
df3$country <- "Germany"


# uk
uk<-read.csv("uk2.csv", header = T, sep = ",")
names(uk)
uk <- rename(uk, referendum="referendum...United.Kingdom.")
uk <- rename(uk, constitution="european.constitution...United.Kingdom.")
uk <- rename(uk, week=Week)

df4 <- uk %>%
  select(week, referendum, constitution) %>%
  gather(key = "variable", value = "value", -week)
head(df4)
df4$country <- "United Kingdom"


# spain
spa<-read.csv("spain2.csv", header = T, sep = ",")
names(spa)
spa <- rename(spa, referendum="referendum...Spain.")
spa <- rename(spa, constitution="Constitucion.Europea...Spain.")
spa <- rename(spa, week=Week)

df5 <- spa %>%
  select(week, referendum, constitution) %>%
  gather(key = "variable", value = "value", -week)
head(df5)
df5$country <- "Spain"


# portugal
por<-read.csv("portugal2.csv", header = T, sep = ",")
names(por)
por <- rename(por, referendum="referendo...Portugal.")
por <- rename(por, constitution="Constitu_Europeia...Portugal.")
por <- rename(por, week=Week)

df6 <- por %>%
  select(week, referendum, constitution) %>%
  gather(key = "variable", value = "value", -week)
head(df6)
df6$country <- "Portugal"

df<-rbind(df1,df2,df3,df4,df5,df6)

table(df$value)
df$value[df$value=="<1"]<-0.5
str(df$value)
df$value<-as.numeric(df$value)

table(df$week)

df$week<-as.Date(df$week)
df$country<-as.factor(df$country)

# Multiple line plot
Sys.setlocale(locale="es_ES.UTF-8")
ggplot(df, aes(x = week, y = value, group = variable)) + 
  geom_vline(xintercept = as.numeric(as.Date("2005-05-29")), linetype="solid", 
             color = "black", size=.7) +
  geom_line(aes(color=variable, linetype=variable), size=1) +
  scale_linetype_manual(values=c("solid","dashed"))+
  facet_wrap(~ country) +
  theme_bw()+
  theme(legend.position="bottom",legend.title = element_blank(),
       panel.grid = element_blank(),
        axis.text.x = element_text(colour = "grey20", size = 13, angle = 0, hjust = 0.5, vjust = 0.5),
        axis.text.y =  element_text(colour = "grey20", size = 13),
        text = element_text(size = 18),
      legend.margin=margin(0,0,0,0),
        legend.box.margin=margin(-15,10,10,10)) +
  ylab("Relative value (max=100)")+ xlab("") + 
  scale_x_date(date_breaks = "6 months",date_labels = "%b'%y")
ggsave("/Users/malet/Dropbox/Contagion paper/Graphs/google_trends.eps", 
       width = 23, height =  15, units = "cm")



###
## EUROBAROMETER DATA
###
rm(list = ls())

setwd("/Users/malet/Dropbox/Contagion paper/Analyses")
dat<-read.dta13("/Users/malet/Dropbox/Contagion paper/Replication files/eurobarometer_final.dta")


## FIGURE 2
# LOESS graph: heard about the constitution
table(dat$heard_about)
heard<-dat%>%group_by(timing, post_fra)%>%summarise(heard=mean(heard_about, na.rm = TRUE),
                                                  size=n())
heard<-heard[-1,]

ggplot(data = dat, aes(x=timing, y=heard_about)) +
  geom_point(data=subset(heard, post_fra==0), aes(y=heard,x=timing, color=post_fra, size=size)) +
  geom_point(data=subset(heard, post_fra==1), aes(y=heard,x=timing, color=post_fra, size=size)) +
  scale_size_area() +
  geom_smooth(data = subset(dat, post_fra==0)) + 
  geom_smooth(data = subset(dat, post_fra==1)) + 
  theme_bw()+  theme(legend.position = "none", text = element_text(size = 18)) + 
  ylab("Heard about the Constitution") + xlab("Days from the French referendum")
#ggsave("/Users/malet/Dropbox/Contagion paper/Graphs/heard_about.eps", device = cairo_ps,
#       width = 15, height =  15, units = "cm")


## FIGURE 3
# LOESS graph with 4-point scale 
sup<-dat%>%group_by(timing, post_fra)%>%summarise(sup=mean(support_const, na.rm = TRUE),
                                                  size=dplyr::n())

ggplot(data = dat, aes(x=timing, y=support_const)) +
  geom_point(data=subset(sup, post_fra==0), aes(y=sup,x=timing, color=post_fra, size=size)) +
  geom_point(data=subset(sup, post_fra==1), aes(y=sup,x=timing, color=post_fra, size=size)) +
  scale_size_area() +
  geom_smooth(data = subset(dat, post_fra==0))+ 
  geom_smooth(data = subset(dat, post_fra==1))+ 
  theme_bw()+  theme(legend.position = "none", text = element_text(size = 18)) + 
  ylab("Support for the Constitution") + xlab("Days from the French referendum")
#ggsave("/Users/malet/Dropbox/Contagion paper/Graphs/support_const.eps", device = cairo_ps,
#       width = 15, height =  15, units = "cm")


## FIGURE A3
# LOESS graph with dichotomous DV
sup<-dat%>%group_by(timing, post_fra)%>%summarise(sup=mean(support_constD, na.rm = TRUE),
                                                  size=dplyr::n())

ggplot(data = dat, aes(x=timing, y=support_constD)) +
  geom_point(data=subset(sup, post_fra==0), aes(y=sup,x=timing, color=post_fra, size=size)) +
  geom_point(data=subset(sup, post_fra==1), aes(y=sup,x=timing, color=post_fra, size=size)) +
  scale_size_area() +
  geom_smooth(data = subset(dat, post_fra==0)) + 
  geom_smooth(data = subset(dat, post_fra==1)) + 
  theme_bw()+  theme(legend.position = "none", text = element_text(size = 18)) + 
  ylab("Support for the Constitution") + xlab("Days from the French referendum")
#ggsave("/Users/malet/Dropbox/Contagion paper/Graphs/support_constD.eps", device = cairo_ps,
#       width = 15, height =  15, units = "cm")




# FUGURE A2 - BALANCE PLOT
df <- dat %>% select(id, post_fra, age, age_squared, education,female,community_type,
                     newspaper,radleft,left,center,right,radright,
                     social_class,personal_situation,religiosity,country)

df <- df[complete.cases(df), ]

df$education <- as.factor(df$education)
df$personal_situation <- as.factor(df$personal_situation)

df <- dummy_cols(df, remove_first_dummy = TRUE)
df <- rename(df, country_UnitedKingdom='country_United Kingdom')
df <- rename(df, community_type_RuralArea='community_type_Rural area or village',
             community_type_SmallTown='community_type_Small or middle sized town',
             social_class_Managers='social_class_Managers (10 to 12 in V414)',
             social_class_ManualWorkers='social_class_Manual workers (15 to 18 in V414)',
             social_class_OtherWhiteCollars='social_class_Other white collars (13 or 14 in V414)',
             social_class_Retired='social_class_Retired (4 in V414)',
             social_class_SelfEmployed = 'social_class_Self-employed (5 to 9 in V414)',
             social_class_Students='social_class_Students (2 in V414)',
             social_class_Unemployed='social_class_Unemployed (3 in V414)')

X  <- select(df, -id, -post_fra, -education, -country, -community_type, -social_class, -personal_situation)
Treatment <- df$post_fra

eb.out<-ebalance(Treatment, X, base.weight = NULL, 
                 norm.constant = NULL, coefs = NULL, 
                 max.iterations = 200, 
                 constraint.tolerance = .1, print.level = 3)

bal.tab(eb.out,Treatment ~ X)

W.out <- weightit(Treatment ~ X, 
                  method = "ebal", estimand = "ATT")

old.labels<-names(X)
new.labels <- c("age","age squared","female","newspaper reader",
                "radical left","left","center","right",
                "radical right","religiosity","low education","medium education",
                "high education","rural area","small town","managers",       
                "manual workers","other white collars","retired","self-employed", 
                "students","unemployed","worse job situation","same job situation",          
                "Italy","Luxembourg","Denmark","Ireland","Greece","Spain","Portugal","Finland" ,            
                "Sweden","Austria","Germany","United Kingdom")

v <- as.data.frame(cbind(old.labels,new.labels))
str(v)
love.plot(W.out, stats = c("mean.diffs"), 
          threshold = c(m = .1), 
          binary = "std", abs = TRUE,var.names = v,
          limits = c(0, 1), grid = FALSE, wrap = 20,
          sample.names = c("Unmatched","Matched"),
          position = "top", shapes = c("circle","triangle"),
          colors = c("red","blue"))
ggsave("/Users/malet/Dropbox/Contagion paper/Graphs/balance_plot.eps", device = cairo_ps,
      width = 15, height =  15, units = "cm")




